package site.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.n3r.eql.EqlPage;

import site.annotations.LoginIgnoreMethod;
import site.annotations.LoginVerifyAction;
import site.config.CommonConfig;
import site.obj.Essay;
import site.obj.YearsCounts;
import site.service.EssayService;
import site.util.Collections;
import site.util.CommonUtils;
import site.util.Struts2Utils;
import site.util.UploadCommon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.Base64;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.opensymphony.xwork2.ActionSupport;
@LoginVerifyAction
public class EssayAction extends ActionSupport {
    private String type;
    private Map retMap;
    private List<Essay> essayList;
    private Essay essay;
    private List<YearsCounts> tabList;
    private String tab;

    // 分页
    private String currentPage;
    EqlPage eqlPage = new EqlPage();

    private File imgFile;
    private String imgFileFileName;
    private String imgFileContentType;
    private static final String RES_PATH = CommonConfig.RES_PATH;
    private static final String UPLOAD_PATH = CommonConfig.UPLOAD_PATH;

    @Resource
    private EssayService productService;

    @Action(value = "/essay/add", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/EssayAdd.ftl") })
    public String init() {
        String typeParam = Struts2Utils.getParameter("type");
        type = typeParam.isEmpty() ? "2" : typeParam;
        return SUCCESS;
    }

    @Action(value = "/addEssay", results = { @Result(name = SUCCESS, type = "json", params = {
            "root", "retMap" }) })
    public String addEssay() throws Exception {

        String type = Struts2Utils.getParameter("type").isEmpty() ? "2" : Struts2Utils.getParameter("type");
        String essayTitle = Struts2Utils.getParameter("essayTitle");
        String essayMiao = Struts2Utils.getParameter("essayMiao");
        String essayDesc = Struts2Utils.getParameter("essayDesc");

        if (StringUtils.isEmpty(essayTitle)) {
            retMap = Collections.asMap("result", "标题不能为空");
            return SUCCESS;
        }

        if (StringUtils.isEmpty(essayMiao)) {
            retMap = Collections.asMap("result", "描述不能为空");
            return SUCCESS;
        }

        if (StringUtils.isEmpty(essayDesc)) {
            retMap = Collections.asMap("result", "内容不能为空");
            return SUCCESS;
        }

        Map inMap = Maps.newHashMap();
        inMap.put("type", type);
        inMap.put("essayTitle", essayTitle);
        inMap.put("essayMiao", essayMiao);
        inMap.put("essayDesc", essayDesc.getBytes("UTF-8"));

        productService.saveEssay(inMap);
        retMap = Collections.asMap("result", "success");
        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/essay", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/Essay.ftl") })
    public String queryEssay() {
        type = "2";
        retMap = Collections.asMap("type", type);
        tabList = productService.queryTab(retMap);
        retMap.put("year", tabList.isEmpty() ? "2015" : tabList.get(0).getCreateYear());
        essayList = productService.queryYearEssay(retMap);
        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/activity", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/Essay.ftl") })
    public String queryActivity() {
        type = "4";
        retMap = Collections.asMap("type", type);
        tabList = productService.queryTab(retMap);
        retMap.put("year", tabList.isEmpty() ? "2015" : tabList.get(0).getCreateYear());
        essayList = productService.queryYearEssay(retMap);
        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/queryTabEssay", results = { @Result(name = SUCCESS, type = "json", params = {
            "root", "essayList" }) })
    public String queryTabEssay() {
        type = Struts2Utils.getParameter("type").isEmpty() ? "2" : Struts2Utils.getParameter("type");
        retMap = Collections.asMap("type", type);
        tabList = productService.queryTab(retMap);
        retMap.put("year", Struts2Utils.getParameter("tabValue"));
        essayList = productService.queryYearEssay(retMap);
        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/queryTabMore", results = { @Result(name = SUCCESS, type = "json", params = {
            "root", "essayList" }) })
    public String queryTabMore() {
        eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
        String totle = Struts2Utils.getParameter("currentTotle").isEmpty() ? "10" : Struts2Utils.getParameter("currentTotle");
        int i = Integer.parseInt(totle)/CommonConfig.PAGE_ROWS + 1;
        eqlPage.setCurrentPage(i);

        type = Struts2Utils.getParameter("type").isEmpty() ? "2" : Struts2Utils.getParameter("type");


        if(i > 1){
            retMap = Collections.asMap("type", type,"year",Struts2Utils.getParameter("tabValue"));
            essayList = productService.queryYearMore(retMap,eqlPage);
        }else{
            essayList = null;
        }

        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/queryOnePro", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/EssayView.ftl") })
    public String queryOnePro() {
        String prodId = Struts2Utils.getParameter("prodId");
        essay = productService.queryEssayById(prodId);
        return SUCCESS;
    }

    @Action(value = "/essay/list", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/EssayList.ftl") })
    public String essayList() {
        // 分页
        eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
        eqlPage.setCurrentPage(1);
        if (!Strings.isNullOrEmpty(currentPage)) {
            eqlPage.setCurrentPage(Integer.parseInt(currentPage));
        }

        type = "2";
        retMap = Collections.asMap("type", type);
        essayList = productService.queryEssay(retMap, eqlPage);

        //分页需返回的数据
        retMap = Collections.asMap("totalPages", eqlPage.getTotalPages(), "totalSize",
                eqlPage.getTotalRows(), "currentPage", eqlPage.getCurrentPage());

        return SUCCESS;
    }

    @Action(value = "/activity/list", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/EssayList.ftl") })
    public String activityList() {
        // 分页
        eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
        eqlPage.setCurrentPage(1);
        if (!Strings.isNullOrEmpty(currentPage)) {
            eqlPage.setCurrentPage(Integer.parseInt(currentPage));
        }

        type = "4";
        retMap = Collections.asMap("type", type);
        essayList = productService.queryEssay(retMap, eqlPage);

        //分页需返回的数据
        retMap = Collections.asMap("totalPages", eqlPage.getTotalPages(), "totalSize",
                eqlPage.getTotalRows(), "currentPage", eqlPage.getCurrentPage());
        return SUCCESS;
    }

    @Action(value = "/deleteEssay", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/EssayList.ftl") })
    public String deleteEssay() {
        // 分页
        eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
        eqlPage.setCurrentPage(1);
        if (!Strings.isNullOrEmpty(currentPage)) {
            eqlPage.setCurrentPage(Integer.parseInt(currentPage));
        }

        String prodId = Struts2Utils.getParameter("prodId");
        String typeParam = Struts2Utils.getParameter("type");

        productService.deleteEssay(prodId);
        retMap = Collections.asMap("type", typeParam.isEmpty() ? "2" : typeParam);
        essayList = productService.queryEssay(retMap, eqlPage);

        //分页需返回的数据
        retMap = Collections.asMap("totalPages", eqlPage.getTotalPages(), "totalSize",
                eqlPage.getTotalRows(), "currentPage", eqlPage.getCurrentPage());
        return SUCCESS;
    }

    @Action(value = "/editEssay", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/essay/EssayEdit.ftl") })
    public String editEssay() {
        String prodId = Struts2Utils.getParameter("prodId");
        essay = productService.queryEssayById(prodId);
        return SUCCESS;
    }

    @Action(value = "/saveEssayOne", results = { @Result(name = SUCCESS, type = "json", params = {
            "root", "retMap" }) })
    public String saveEssayOne() throws Exception {
        String prodId = Struts2Utils.getParameter("prodId");
        String essayTitle = Struts2Utils.getParameter("essayTitle");
        String essayMiao = Struts2Utils.getParameter("essayMiao");
        String essayDesc = Struts2Utils.getParameter("essayDesc");

        if (StringUtils.isEmpty(essayTitle)) {
            retMap = Collections.asMap("result", "标题不能为空");
            return SUCCESS;
        }

        if (StringUtils.isEmpty(essayMiao)) {
            retMap = Collections.asMap("result", "描述不能为空");
            return SUCCESS;
        }

        if (StringUtils.isEmpty(essayDesc)) {
            retMap = Collections.asMap("result", "内容不能为空");
            return SUCCESS;
        }

        retMap = new HashMap();
        retMap.put("prodId", prodId);
        retMap.put("essayTitle", essayTitle);
        retMap.put("essayMiao", essayMiao);
        retMap.put("essayDesc", essayDesc.getBytes("UTF-8"));

        productService.updateEssay(retMap);
        retMap = Collections.asMap("result", "success");
        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/fileupload")
    public String fileupload() {
        String path = CommonUtils.getImgUploadPath();

        String newFileName = renameFile();
        try {
            byte[] imageByte = FileUtils.readFileToByteArray(imgFile);
            File imageFile = new File(path + newFileName);
            FileUtils.writeByteArrayToFile(imageFile, imageByte);
            String fileViewPath = RES_PATH + UPLOAD_PATH + newFileName;
            print(JSON.toJSONString(Collections.asMap("error", 0, "url", fileViewPath)));
        } catch (Exception e) {

        }
        return NONE;
    }

    /**
     * 重命名文件.
     */
    private String renameFile() {
        String extName = ""; // 文件拓展名
        if (imgFileFileName.lastIndexOf(".") >= 0) {
            extName = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
        }
        String newFileName = UploadCommon.getCurrDate("yyyyMMddHHmmss") + UploadCommon.getRannum() + extName; //保存新的文件名
        return newFileName;
    }

    /**
     * 得到经过Base64解码的图像二进制数据
     */
    public byte[] getImgData(String fileUrl) {
        /*
         * 利用canvas元素的toDataURL("image/jpeg")方法生成的图像地址格式为：
         *  第一部分：data:image/jpeg;base64
         *  中间一个逗号
         *  第二部分：一个经过base64编码的字符串，通过Base64解码后即可得到该图像原始二进制数据
         */
        String[] data = fileUrl.split(",");//这里fileUrl就是前台toDataURL（）方法传过来的数据
        return Base64.decodeFast(data[1]);
    }

    private void print(String str) {
        PrintWriter out = null;
        try {
            ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
            ServletActionContext.getResponse().setHeader("Cache-Control", "no-cache");
            ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
            out = ServletActionContext.getResponse().getWriter();
            out.print(str);
            out.flush();
        } catch (IOException e) {
        } finally {
            out.close();
        }
    }

    public String getTab() {
        return tab;
    }

    public void setTab(String tab) {
        this.tab = tab;
    }

    public List<YearsCounts> getTabList() {
        return tabList;
    }

    public void setTabList(List<YearsCounts> tabList) {
        this.tabList = tabList;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Map getRetMap() {
        return retMap;
    }

    public void setRetMap(Map retMap) {
        this.retMap = retMap;
    }

    public List<Essay> getEssayList() {
        return essayList;
    }

    public void setEssayList(List<Essay> essayList) {
        this.essayList = essayList;
    }

    public Essay getEssay() {
        return essay;
    }

    public void setEssay(Essay essay) {
        this.essay = essay;
    }

    public File getImgFile() {
        return imgFile;
    }

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public String getImgFileContentType() {
        return imgFileContentType;
    }

    public void setImgFileContentType(String imgFileContentType) {
        this.imgFileContentType = imgFileContentType;
    }

    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }

    public String getImgFileFileName() {
        return imgFileFileName;
    }

    public String getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(String currentPage) {
        this.currentPage = currentPage;
    }
}
